﻿using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Modularity;
using Volo.Abp;
using Elsa.EntityFrameworkCore.Modules.Management;
using Elsa.EntityFrameworkCore.Modules.Runtime;
using Elsa.Extensions;
using Volo.Abp.Autofac;
using Microsoft.OpenApi.Models;
using Himp.Platform.ApiGateway.Controllers;

namespace Himp.Platform.ApiGateway
{
    [DependsOn(typeof(AbpAspNetCoreMvcModule))]
    [DependsOn(typeof(AbpAutofacModule))]
    public class AppModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();
            var hostingEnvironment = context.Services.GetHostingEnvironment();
            context.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            context.Services.AddEndpointsApiExplorer();

            context.Services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo { Title = "Platform API", Version = "v1" });
                options.DocInclusionPredicate((docName, description) => true);
                options.CustomSchemaIds(type => type.FullName);
            });

            context.Services.AddElsa(elsa =>
            {
                // Configure Management layer to use EF Core.
                elsa.UseWorkflowManagement(management => management.UseEntityFrameworkCore());

                // Configure Runtime layer to use EF Core.
                elsa.UseWorkflowRuntime(runtime => runtime.UseEntityFrameworkCore());

                // Default Identity features for authentication/authorization.
                elsa.UseIdentity(identity =>
                {
                    identity.TokenOptions = options => options.SigningKey = "sufficiently-large-secret-signing-key"; // This key needs to be at least 256 bits long.
                    identity.UseAdminUserProvider();
                });

                // Configure ASP.NET authentication/authorization.
                elsa.UseDefaultAuthentication(auth => auth.UseAdminApiKey());

                // Expose Elsa API endpoints.
                elsa.UseWorkflowsApi();

                // Setup a SignalR hub for real-time updates from the server.
                elsa.UseRealTimeWorkflows();

                // Enable C# workflow expressions
                elsa.UseCSharp();

                // Enable JavaScript workflow expressions
                elsa.UseJavaScript(options => options.AllowClrAccess = true);

                // Enable HTTP activities.
                elsa.UseHttp(options => options.ConfigureHttpOptions = httpOptions => httpOptions.BaseUrl = new Uri("https://localhost:5001"));

                // Use timer activities.
                elsa.UseScheduling();

                // Register custom activities from the application, if any.
                //elsa.AddActivitiesFrom<Program>();

                // Register custom workflows from the application, if any.
                //elsa.AddWorkflowsFrom<Program>();
                elsa.AddWorkflow<WeatherForecastWorkflow>();

                // Register custom webhook definitions from the application, if any.
                //elsa.UseWebhooks(webhooks => webhooks.WebhookOptions = options => context.Configuration.GetSection("Webhooks").Bind(options));
            });
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();
            var env = context.GetEnvironment();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCorrelationId();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCors();
            app.UseAuthentication();

            app.UseUnitOfWork();
            app.UseDynamicClaims();
            app.UseAuthorization();
            app.UseSwagger();
            app.UseSwaggerUI();
            app.UseWorkflowsApi(); // Use Elsa API endpoints.
            app.UseWorkflows();
            app.UseAbpSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Platform API");
                //var configuration = context.GetConfiguration();
                //options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
                //options.OAuthScopes("Platform");
            });

            app.UseAuditing();
            app.UseConfiguredEndpoints(endpoints =>
            {

            });
        }
    }
}
